package com.lbs.jiepiaisi.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.AMapNaviViewListener;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.enums.NaviType;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.navi.model.AMapCalcRouteResult;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapModelCross;
import com.amap.api.navi.model.AMapNaviCameraInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviRouteNotifyData;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AMapServiceAreaInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseNaviActivity;
import com.lbs.jiepiaisi.bean.LatLngEntity;
import com.lbs.jiepiaisi.utils.Constant;
import java.util.ArrayList;
import java.util.List;
/**
 *
 * 时间：2017/9/29 15:23
 * 作用：开始导航
 */
public class AccountStartNaviActivity extends Activity implements AMapNaviListener,
        AMapNaviViewListener,AMapLocationListener {
    //算路终点坐标
    protected NaviLatLng mEndLatlng;
    //算路起点坐标
    protected NaviLatLng mStartLatlng;

    //存储算路起点的列表
    protected final List<NaviLatLng> sList = new ArrayList<NaviLatLng>();
    //存储算路终点的列表
    protected final List<NaviLatLng> eList = new ArrayList<NaviLatLng>();
    /** 3D导航地图对象 */
    private AMapNaviView mAMapNaviView;
    /** 导航对象 */
    private AMapNavi mAMapNavi;
//    /** 途经点坐标 */
//    private List<NaviLatLng> mWayPointList = new ArrayList<NaviLatLng>();
//    /** 声明mLocationOption对象 */
//    private AMapLocationClientOption mLocationOption = null;
//    /** 声明mlocationClient对象 */
//    private AMapLocationClient mlocationClient = null;
    /** 导航方式 (驾车模式)*/
    private int routeType;
    /** 线程句柄 */
    private Handler handler = new Handler();

    private LinearLayout back;

    private TextToSpeech tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {

            }
        });
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String getGdLat = bundle.getString("getGdLat");
        String getGdLng=bundle.getString("getGdLng");
        double GdLat = Double.parseDouble(getGdLat);
        double GdLng=Double.parseDouble(getGdLng);
        mEndLatlng=new NaviLatLng(GdLat,GdLng);
        String startGdLat=bundle.getString("startGdLat");
        String startGdlng=bundle.getString("startGdlng");
        double SGdLat=Double.parseDouble(startGdLat);
        double SGdLng=Double.parseDouble(startGdlng);
        mStartLatlng=new NaviLatLng(SGdLat,SGdLng);
//        sList.add(mStartLatlng);
//        eList.add(mEndLatlng);
        routeType=bundle.getInt("routeType");
        Log.e("TAG","routeType:"+String.valueOf(routeType));
       // mAMapNaviView = new AMapNaviView(this);

        setContentView(R.layout.activity_start_navi);
        mAMapNaviView = (AMapNaviView)findViewById(R.id.navi_view);
        mAMapNaviView.onCreate(savedInstanceState);
        initNaviData();
        sList.add(mStartLatlng);
        initNavi();

        back  = (LinearLayout)findViewById(R.id.back);

        setAmapNaviViewOptions();
       // mAMapNaviView.setAMapNaviViewListener(this);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        mAMapNaviView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            mAMapNaviView.onPause();
            // 仅仅是停止你当前在说的这句话，一会到新的路口还是会再说的
            //mTtsManager.stopSpeaking();
            // 停止导航之后，会触及底层stop，然后就不会再有回调了，但是讯飞当前还是没有说完的半句话还是会说完
            //mAMapNavi.stopNavi();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        try {
            mAMapNaviView.onDestroy();
            // since 1.6.0 不再在naviview destroy的时候自动执行AMapNavi.stopNavi();请自行执行
            mAMapNavi.stopNavi();
            mAMapNavi.destroy();
         // mTtsManager.destroy();
//            if (null != mlocationClient) {
//                /**
//                 * 如果AMapLocationClient是在当前Activity实例化的，
//                 * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
//                 */
//                mlocationClient.onDestroy();
//                mlocationClient = null;
//                mLocationOption = null;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
    /**
     * 初始化导航
     */
    private void initNavi() {
        // 实例化语音引擎
//        mTtsManager = TTSController.getInstance(getApplicationContext());
//        mTtsManager.init();
//        mTtsManager.startSpeaking();

        mAMapNavi = AMapNavi.getInstance(getApplicationContext());
        mAMapNavi.addAMapNaviListener(this);
        mAMapNavi.setUseInnerVoice(true);
//        mAMapNavi.addAMapNaviListener(mTtsManager);

        // 设置模拟导航的行车速度
        mAMapNavi.setEmulatorNaviSpeed(75);
    }

    /**
     * 设置导航参数
     */
    private void setAmapNaviViewOptions() {
        if (mAMapNaviView == null) {
            return;
        }
        AMapNaviViewOptions viewOptions = new AMapNaviViewOptions();
        // viewOptions.setTilt(0); // 0 表示使用2D地图
        // viewOptions.setSettingMenuEnabled(true);//设置菜单按钮是否在导航界面显示
        // viewOptions.setNaviNight(mDayNightFlag);//设置导航界面是否显示黑夜模式
        viewOptions.setReCalculateRouteForYaw(true);// 设置偏航时是否重新计算路径mDeviationFlag
        // viewOptions.setReCalculateRouteForTrafficJam(mJamFlag);//前方拥堵时是否重新计算路径
        // viewOptions.setTrafficInfoUpdateEnabled(mTrafficFlag);//设置交通播报是否打开
        // viewOptions.setCameraInfoUpdateEnabled(mCameraFlag);//设置摄像头播报是否打开
        // viewOptions.setScreenAlwaysBright(mScreenFlag);//设置导航状态下屏幕是否一直开启。
        // viewOptions.setNaviViewTopic(mThemeStle);//设置导航界面的主题
        mAMapNaviView.setViewOptions(viewOptions);
    }

    /**
     * 初始化导航起始点、途经点参数
     */
    private void initNaviData() {
        if(routeType==2){//2代表驾车模式，3代表步行模式
            eList.add(mEndLatlng);
        }else if(routeType==3){
            eList.add(mEndLatlng);
        }
    }


    @Override
    public void onInitNaviFailure() {
        Toast.makeText(this, "导航初始化失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onInitNaviSuccess() {
        /**
         * 方法: int strategy=mAMapNavi.strategyConvert(congestion,
         * avoidhightspeed, cost, hightspeed, multipleroute); 参数:
         *
         * @congestion 躲避拥堵
         * @avoidhightspeed 不走高速
         * @cost 避免收费
         * @hightspeed 高速优先
         * @multipleroute 多路径
         *
         *  说明:
         *      以上参数都是boolean类型，其中multipleroute参数表示是否多条路线，如果为true则此策略会算出多条路线。
         *      注意: 不走高速与高速优先不能同时为true 高速优先与避免收费不能同时为true
         */
        Log.e("TAG","导航成功！");
        int strategy = 0;
        try {
            strategy = mAMapNavi.strategyConvert(true, false, false, false, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(routeType == 2) {//2代表驾车模式，3代表步行模式
            mAMapNavi.calculateDriveRoute(sList, eList, null, strategy);
        } else if(routeType == 3){
            mAMapNavi.calculateWalkRoute(sList.get(0), eList.get(0)); // 步行导航
        }
    }


    @Override
    public void onStartNavi(int i) {

    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {

    }

    @Override
    public void onGetNavigationText(int i, String s) {

    }

    @Override
    public void onGetNavigationText(String s) {

    }

    @Override
    public void onEndEmulatorNavi() {

    }

    @Override
    public void onArriveDestination() {
//        tts.setPitch(0.0f);// 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
//        tts.speak("到达目的地附近",
//                TextToSpeech.QUEUE_FLUSH, null);
    }


    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {

    }

    @Override
    public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) {

    }

    @Override
    public void updateCameraInfo(AMapNaviCameraInfo[] aMapNaviCameraInfos) {

    }

    @Override
    public void onServiceAreaUpdate(AMapServiceAreaInfo[] aMapServiceAreaInfos) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void hideLaneInfo() {

    }

    /**
     * 路径规划完毕,导航开始
     */
    @Override
    public void onCalculateRouteSuccess(int[] ints) {
        Log.e("TAG","路径规划完毕,导航开始");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean naviType = true; // true表示模拟导航，false表示真实GPS导航（默认true）

                mAMapNavi.startNavi(NaviType.GPS);
            }
        },3000);
    }

    @Override
    public void onCalculateRouteSuccess(AMapCalcRouteResult aMapCalcRouteResult) {
        Log.e("TAG","路径规划完毕,导航开始");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean naviType = true; // true表示模拟导航，false表示真实GPS导航（默认true）
                mAMapNavi.startNavi(NaviType.GPS);
            }
        },3000);
    }

    /////
    @Override
    public void onNaviRouteNotify(AMapNaviRouteNotifyData aMapNaviRouteNotifyData) {

    }

    @Override
    public void onCalculateRouteFailure(int i) {

    }

    @Override
    public void onCalculateRouteFailure(AMapCalcRouteResult aMapCalcRouteResult) {

    }

    /////

    @Override
    public void onNaviViewShowMode(int i) {

    }

    /////

    /////

    @Override
    public void onMapTypeChanged(int i) {

    }

    /////

    @Override
    public void notifyParallelRoad(int i) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {

    }

    @Override
    public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {

    }

    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {

    }

    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {

    }

    @Override
    public void onPlayRing(int i) {

    }

    @Override
    public void onNaviSetting() {

    }

    @Override
    public void onNaviCancel() {

    }

    @Override
    public boolean onNaviBackClick() {
        return false;
    }

    @Override
    public void onNaviMapMode(int i) {

    }

    @Override
    public void onNaviTurnClick() {

    }

    @Override
    public void onNextRoadClick() {

    }

    @Override
    public void onScanViewButtonClick() {

    }

    @Override
    public void onLockMap(boolean b) {

    }

    @Override
    public void onNaviViewLoaded() {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }

    @Override
    public void hideModeCross() {

    }

    @Override
    public void updateIntervalCameraInfo(AMapNaviCameraInfo aMapNaviCameraInfo, AMapNaviCameraInfo aMapNaviCameraInfo1, int i) {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo aMapLaneInfo) {

    }

    @Override
    public void showModeCross(AMapModelCross aMapModelCross) {

    }
}
